/*
 */

// Import the JDBC classes
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class JdbcApplet extends java.applet.Applet implements ActionListener
{
	Connection conn;
	Statement  stmt;
	ResultSet  rest;
	ResultSetMetaData meta;

  // The connect string specific to connection through Oracle 8 Connection Manager.
	String url = "jdbc:oracle:thin:scott/tiger@(description=(address_list=(address=(protocol=tcp)(host=pegasus.cs.csubak.edu)(port=1630))(address=(protocol=tcp)(host=cheval.cs.csubak.edu)(port=1521)))(source_route=yes)(connect_data=(sid=TEST)))";

	Label     lbRowCount = new Label(" No record retrieved ");
	TextField query =  new TextField("select * from emp", 60);
	Button btnExecute;
	TextArea txtOutput;
	StringBuffer output;


  	public void init (){
		this.setLayout (new BorderLayout ());
		Panel p = new Panel ();
		p.setLayout (new FlowLayout ());
		btnExecute = new Button ("Execute");
		btnExecute.addActionListener(this);
		query.addActionListener(this);
		p.add(lbRowCount);
		p.add(query);
		p.add (btnExecute);
		this.add ("North", p);
		txtOutput = new TextArea (10, 60);
		txtOutput.setFont(new Font("Monospaced", Font.PLAIN, 12));
		txtOutput.setForeground(Color.white);
		txtOutput.setBackground(Color.black);
		this.add ("Center", txtOutput);
	}
	void connectToDatabase() {
	   try {
		Class.forName("oracle.jdbc.driver.OracleDriver");
		conn = DriverManager.getConnection (url, "scott", "tiger");
	   } catch (SQLException e) { attachErrors(e); }
	     catch (ClassNotFoundException cnfEx) { cnfEx.printStackTrace(); }
	}

	void executeSQL(String sql) {
	   try {
		if ( sql.charAt(sql.length() -1) == ';' ) sql = sql.substring(0, sql.length() -1);
		stmt = conn.createStatement();
		rest = stmt.executeQuery(sql);
		meta = rest.getMetaData();
	   } catch (SQLException e) { attachErrors(e); }
	}

	void displayResultSet() {
	   try {
		int colCnt = meta.getColumnCount();
		int colWidths[] = getColumnWidths(colCnt);

		output = new StringBuffer();
		displayColumnHeaders(colCnt, colWidths);

		int cnt = 0;
		while ( rest.next() ) {
			for ( int i = 1; i <= colCnt; i ++ )
				output.append(ScreenIO.expandString(rest.getString(i),
						colWidths[i-1]) + " ") ;
			output.append("\n");
			cnt++;
		}	
		lbRowCount.setText(cnt + " records retrieved ");
		stmt.close();
	   } catch (SQLException e) { attachErrors(e); }
	     catch (NullPointerException e ) { output.append("Null pointer in display result set."); }
	}

	void displayColumnHeaders(int cnt, int colWidths[]) {
	   try {
		for ( int i = 1; i <= cnt; i ++ )
			output.append(ScreenIO.expandString(meta.getColumnName(i),
				colWidths[i-1]) + " ");
		output.append("\n");

		for ( int i = 1; i <= cnt; i ++ ) {
			for ( int j = 0; j < colWidths[i-1]; j ++ ) output.append("=");
			output.append(" ");
		}
		output.append("\n");
	   } catch (SQLException e ) { attachErrors(e); }
	
	}

	int [] getColumnWidths( int colCnt ) {
		if ( colCnt < 1 ) return null;
		int [] widthArr = new int[colCnt];
		for ( int i = 1; i <= colCnt; i ++ ) {
		   try {
			widthArr[i-1] = meta.getColumnDisplaySize(i);
			switch( meta.getColumnType(i) ) {
			   case Types.NUMERIC: widthArr[i-1] = 10; break;
			   case Types.DECIMAL: widthArr[i-1] = 10; break;
			   case Types.DATE: widthArr[i-1] = 10; break;
			   case Types.TIME: widthArr[i-1] = 10; break;
			   case Types.TIMESTAMP: widthArr[i-1] = 10; break;
			}
		   } catch (SQLException e) {}
		}
		return widthArr;
	}


	public void stop () {
		try { conn.close(); } catch (SQLException sqlEx) {}
	}

	public void actionPerformed (ActionEvent ev) {
		try { if (conn == null || conn.isClosed() ) connectToDatabase(); }
		catch ( SQLException e ) { attachErrors(e) ; }
		executeSQL(query.getText());
		displayResultSet();
		txtOutput.setVisible(false); // to get rid out flesh on screen.
		txtOutput.setText(new String( output) );
		txtOutput.setVisible(true);
      	}

	void attachErrors(SQLException e) {
		txtOutput.setText("");
		while ( e != null ) {
			output.append (e.getMessage());
			e = e.getNextException();
		}
	}
}

